package com.twu.biblioteca.ui;

import com.twu.biblioteca.data.BibliotecaItem;
import com.twu.biblioteca.data.BibliotecaItemDAO;
import com.twu.biblioteca.exceptions.BibliotecaItemOperationException;

/**
 * Created by florian on 26/12/13.
 */
public abstract class ControllerWithItem implements ScreenController{
    protected final BibliotecaUI ui;
    protected final ScreenControllerFactory controllerFactory;
    protected final BibliotecaItemDAO dao;

    public ControllerWithItem(ScreenControllerFactory controllerFactory, BibliotecaUI ui, BibliotecaItemDAO dao) {
        this.ui = ui;
        this.controllerFactory = controllerFactory;
        this.dao = dao;
        showUsage();

    }

    @Override
    public ScreenController processCommand(String line) {
        try {
            int bookId = Integer.parseInt(line);
            BibliotecaItem item = dao.findItemForId(bookId);
            if (item!=null) {
                try {
                    return handleWithItem(item);
                } catch (BibliotecaItemOperationException e) {
                    return handleError();
                }
            }else {
                return handleError();

            }
        } catch (NumberFormatException e) {
            return handleError();
        }
    }

    protected abstract void showUsage();

    protected abstract ScreenController handleWithItem(BibliotecaItem book) throws BibliotecaItemOperationException;

    protected abstract ScreenController handleError();
}
